<template>
  <view class="container">
    <!-- 用户信息区域 -->
    <view class="header-section">
      <view class="avatar-container">
        <image 
          class="avatar" 
          :src="userInfo.avatar || '/static/avatar/default.png'" 
          mode="aspectFill"
        ></image>
      </view>
      <view class="user-basic-info">
        <text class="user-name">{{ userInfo.customerName || '未命名用户' }}</text>
        <text class="user-type">{{ getUserTypeLabel(userInfo.type) }}</text>
        <text class="user-id">ID: {{ userInfo.id || '000000' }}</text>
        <text class="user-phone" v-if="userInfo.phone">手机号: {{ userInfo.phone }}</text>
      </view>
    </view>

    <!-- 统计数据区域 -->
    <view class="stats-section">
      <view class="stat-item" v-for="(item, index) in statList" :key="index" @tap="goToOrdersWithStatus(item.status)">
        <text class="stat-value">{{ item.value }}</text>
        <text class="stat-label">{{ item.label }}</text>
      </view>
    </view>

    <!-- 功能菜单区域 -->
    <view class="menu-section">
      <view class="menu-item" @tap="goToEditProfile">
        <text class="menu-icon">👤</text>
        <text class="menu-text">个人信息</text>
        <text class="menu-arrow">→</text>
      </view>

      <view class="menu-item" @tap="goToOrders">
        <text class="menu-icon">📋</text>
        <text class="menu-text">我的订单</text>
        <text class="menu-arrow">→</text>
      </view>

      <view class="menu-item" @tap="goToMessages">
        <text class="menu-icon">💬</text>
        <text class="menu-text">消息通知</text>
        <view class="badge" v-if="userInfo.unreadMsgCount > 0">
          {{ userInfo.unreadMsgCount }}
        </view>
        <text class="menu-arrow">→</text>
      </view>

      <view class="divider"></view>

      <view class="menu-item" @tap="goToSettings">
        <text class="menu-icon">⚙️</text>
        <text class="menu-text">设置</text>
        <text class="menu-arrow">→</text>
      </view>

      <view class="menu-item logout" @tap="logout">
        <text class="menu-icon">🚪</text>
        <text class="menu-text">退出登录</text>
        <text class="menu-arrow">→</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { getWorkOrderListByCustomerIdAPI } from '@/api/order.js'

const userInfo = ref({})
const router = useRouter()
const orders = ref([])

// 用户统计数据
const statList = computed(() => [
  { label: '进行中', value: orderCounts.value.ongoing, status: 'ongoing' },
  { label: '未支付', value: orderCounts.value.unpaid, status: 'unpaid' },
  { label: '待评论', value: orderCounts.value.pendingComment, status: 'pendingComment' },
  { label: '历史订单', value: orderCounts.value.history, status: 'history' },
  { label: '已取消', value: orderCounts.value.cancelled, status: 'cancelled' }
])

// 计算订单各状态的数量
const orderCounts = computed(() => {
  // 与订单页面保持完全一致的统计逻辑
  const counts = {
    ongoing: 0,
    unpaid: 0,
    pendingComment: 0,
    history: 0,
    cancelled: 0
  }
  
  orders.value.forEach(order => {
    // 先确定订单属于哪个tab，再进行统计
    let tab = 'history'
    if (order.status === 0 || order.status === 1) {
      tab = 'ongoing'
    } else if (order.payStatus === 0 && order.status === 2) {
      tab = 'unpaid'
    } else if (order.status === 2 && order.payStatus === 1) {
      tab = 'pendingComment'
    } else if ((order.payStatus === 1 && order.status === 4) || order.status === 1) {
      tab = 'history'
    } else if (order.status === 3) {
      tab = 'cancelled'
    }
    
    // 根据tab进行计数
    counts[tab]++
  })
  
  return counts
})

onMounted(() => {
  // 获取用户信息
  const info = uni.getStorageSync('userInfo') || {}
  console.log('从本地存储获取的用户信息:', info)
  userInfo.value = {
    avatar: '/static/avatar/default.png',
    customerName: info.customerName || '未命名用户',
    type: info.type || '普通客户',
    id: info.id || '',
    unreadMsgCount: info.unreadMsgCount || 0,
    ...info
  }
  console.log('初始化后的用户信息:', userInfo.value)

  // 未登录跳转登录页
  if (!info.id) {
    router.push('/pages/login/login')
  } else {
    // 如果用户已登录，从服务器获取最新用户信息
    fetchUserInfo(info.id)
  }
  
  // 获取订单数据
  fetchOrders()
})

// 获取最新的用户信息
const fetchUserInfo = async (userId) => {
  try {
    // 导入获取用户信息的API
    const { getCustomerInfoAPI } = await import('@/api/user.js')
    
    // 调用API获取用户信息
    const res = await getCustomerInfoAPI(userId)
    
    if (res && res.code === 0 && res.data) {
      // 更新用户信息
      userInfo.value = {
        ...userInfo.value,
        ...res.data
      }
      
      // 同时更新本地存储的用户信息
      uni.setStorageSync('userInfo', userInfo.value)
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    uni.showToast({
      title: '获取用户信息失败',
      icon: 'none'
    })
  }
}

// 获取用户类型标签
const getUserTypeLabel = (type) => {
  const typeMap = {
    'personal': '个人客户',
    'enterprise': '企业客户',
    '普通客户': '普通客户',
    '企事业用户': '企事业用户'
  }
  return typeMap[type] || '普通客户'
}

// 获取订单列表
const fetchOrders = async () => {
  try {
    // 获取本地存储的用户信息
    const userInfo = uni.getStorageSync('userInfo');
    
    // 如果用户已登录且有ID，则获取该用户的订单列表
    if (userInfo && userInfo.id) {
      const res = await getWorkOrderListByCustomerIdAPI(userInfo.id);
      
      // 处理接口返回的数据
      if (res && Array.isArray(res)) {
        orders.value = res.map(item => {
          return {
            ...item,
            // 确保必要的字段存在
            id: item.id || '',
            type: item.type || item.title || '',
            address: item.address || '',
            time: item.createTime || item.updateTime || '',
            price: item.price || 0,
            status: item.status !== undefined ? item.status : 0,
            payStatus: item.payStatus !== undefined ? item.payStatus : 0
          }
        })
      }
    }
  } catch (error) {
    console.error('获取订单列表失败:', error)
    uni.showToast({
      title: '获取订单数据失败',
      icon: 'none'
    })
  }
}

// 跳转到订单页面
const goToOrders = () => {
  uni.switchTab({
    url: '/pages/orders/orders'
  })
}

// 跳转到带状态筛选的订单页面
const goToOrdersWithStatus = (status) => {
  uni.switchTab({
    url: `/pages/orders/orders?status=${status}`
  })
}

// 跳转到消息页面
const goToMessages = () => {
  // 暂时跳转到订单页面作为示例
  uni.navigateTo({
    url: '/pages/orders/orders',
    animationType: 'slide-in-right',
    animationDuration: 300
  })
}

// 跳转到编辑个人信息页面
const goToEditProfile = () => {
  uni.navigateTo({
    url: '/pages/edit-profile/edit-profile'
  })
}

// 跳转到设置页面
const goToSettings = () => {
  // 这里可以跳转到其他设置相关页面
  uni.showToast({
    title: '功能开发中',
    icon: 'none'
  })
}

// 退出登录
const logout = () => {
  uni.showModal({
    title: '确认退出',
    content: '确定要退出登录吗？',
    confirmText: '确认退出',
    cancelText: '取消',
    confirmColor: '#FF4D4F',
    success: (res) => {
      if (res.confirm) {
        // 显示加载提示
        uni.showLoading({ title: '退出中...' })
        
        // 清除本地存储
        uni.removeStorageSync('userInfo')
        
        // 延迟跳转
        setTimeout(() => {
          uni.hideLoading()
          // 使用 uni.reLaunch 确保正确跳转到登录页
          uni.reLaunch({
            url: '/pages/login/login'
          })
          uni.showToast({ title: '已退出登录', icon: 'none' })
        }, 800)
      }
    }
  })
}
</script>

<style scoped>
.container {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding: 20rpx;
}

.header-section {
  background: linear-gradient(135deg, #1677ff 0%, #0e62d4 100%);
  border-radius: 20rpx;
  padding: 60rpx 30rpx;
  text-align: center;
  color: white;
  margin-bottom: 20rpx;
}

.avatar-container {
  width: 160rpx;
  height: 160rpx;
  border-radius: 50%;
  border: 6rpx solid rgba(255, 255, 255, 0.3);
  padding: 4rpx;
  margin: 0 auto 30rpx;
  overflow: hidden;
}

.avatar {
  width: 100%;
  height: 100%;
  border-radius: 50%;
}

.user-basic-info {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.user-name {
  font-size: 36rpx;
  font-weight: 600;
  margin-bottom: 5rpx;
}

.user-type {
  font-size: 28rpx;
  background-color: rgba(255, 255, 255, 0.2);
  padding: 5rpx 15rpx;
  border-radius: 30rpx;
  margin-bottom: 10rpx;
}

.user-id {
  font-size: 24rpx;
  opacity: 0.9;
  margin-bottom: 5rpx;
}

.user-phone {
  font-size: 24rpx;
  opacity: 0.9;
  margin-top: 5rpx;
}

.stats-section {
  background-color: white;
  border-radius: 20rpx;
  padding: 30rpx 20rpx;
  display: flex;
  justify-content: space-around;
  margin-bottom: 20rpx;
  box-shadow: 0 5rpx 15rpx rgba(0, 0, 0, 0.05);
}

.stat-item {
  text-align: center;
  flex: 1;
}

.stat-value {
  font-size: 32rpx;
  font-weight: 600;
  color: #1f2937;
  display: block;
  margin-bottom: 10rpx;
}

.stat-label {
  font-size: 22rpx;
  color: #6b7280;
  display: block;
}

.menu-section {
  background-color: white;
  border-radius: 20rpx;
  overflow: hidden;
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.menu-item:last-child {
  border-bottom: none;
}

.menu-icon {
  font-size: 36rpx;
  width: 60rpx;
  margin-right: 20rpx;
}

.menu-text {
  flex: 1;
  font-size: 30rpx;
  color: #333;
}

.menu-arrow {
  color: #ccc;
  font-size: 30rpx;
}

.badge {
  background-color: #ff4d4f;
  color: white;
  border-radius: 50%;
  width: 40rpx;
  height: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 22rpx;
  margin-right: 20rpx;
}

.divider {
  height: 1rpx;
  background-color: #f0f0f0;
  margin: 0 30rpx;
}

.logout {
  color: #ff4d4f;
}
</style>